import { goodsList as list, types } from '@/mock/goods'
import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useGoodsStore = defineStore('goods', () => {
  const goodsList = ref(JSON.parse(localStorage.getItem('goods_list')) || list)
  const idIndex = ref(localStorage.getItem('id_index') || goodsList.value.length)

  const typesList = ref(JSON.parse(localStorage.getItem('types_list')) || types)

  const typesIdIndex = ref(localStorage.getItem('types_id_index') || typesList.value.length - 1)

  const delGoods = id => {
    if (id) {
      goodsList.value = goodsList.value.filter(item => item.id !== id)
      localStorage.setItem('goods_list', JSON.stringify(goodsList.value))
    }
  }

  const modifyGoods = () => {
    localStorage.setItem('goods_list', JSON.stringify(goodsList.value))
  }

  const addGoods = goods => {
    if (goods) {
      goods.id = +idIndex.value + 1
      idIndex.value = goods.id
      goodsList.value.push(goods)
      localStorage.setItem('goods_list', JSON.stringify(goodsList.value))
      localStorage.setItem('id_index', idIndex.value)
    }
  }

  const delType = id => {
    if (id) {
      typesList.value = typesList.value.filter(item => item.id !== id)
      localStorage.setItem('types_list', JSON.stringify(typesList.value))
    }
  }

  const modifyType = (id, newType) => {
    if (id) {
      const result = typesList.value.find(item => item.id === id)
      result.type = newType
      localStorage.setItem('types_list', JSON.stringify(typesList.value))
    }
  }

  const addType = type => {
    if (type) {
      type.id = +typesIdIndex.value + 1
      typesIdIndex.value = type.id
      typesList.value.push(type)
      localStorage.setItem('types_list', JSON.stringify(typesList.value))
      localStorage.setItem('types_id_index', typesIdIndex.value)
    }
  }

  return {
    goodsList,
    typesList,
    delGoods,
    addGoods,
    modifyGoods,
    delType,
    addType,
    modifyType
  }
})
